﻿// 文件使用MiniExcel源码， 使用时需遵循其 Apache License 2.0
// 修改摘要通知： 删除异步、Task等net2.0中不支持的内容，替换原先C#自带的zip处理方式，改用yacomp 进行解压缩。
using ExcelConfig.Utils;
using System;
using System.Collections.Generic;
using System.Data;

namespace ExcelConfig.WriteAdapter
{
    internal class DataReaderWriteAdapter : IMiniExcelWriteAdapter
    {
        private readonly IDataReader _reader;
        private readonly Configuration _configuration;

        public DataReaderWriteAdapter(IDataReader reader, Configuration configuration)
        {
            _reader = reader;
            _configuration = configuration;
        }

        public bool TryGetKnownCount(out int count)
        {
            count = 0;
            return false;
        }

        public List<ExcelColumnInfo> GetColumns()
        {
            var props = new List<ExcelColumnInfo>();
            for (var i = 0; i < _reader.FieldCount; i++)
            {
                var columnName = _reader.GetName(i);

                if (!_configuration.DynamicColumnFirst)
                {
                    var prop = CustomPropertyHelper.GetColumnInfosFromDynamicConfiguration(columnName, _configuration);
                    props.Add(prop);
                    continue;
                }

                for(var _i=0; _i< _configuration.DynamicColumns.Length; _i++)
                    if (string.Equals(
                        _configuration.DynamicColumns[_i].Key,
                        columnName,
                        StringComparison.OrdinalIgnoreCase))
                    {
                        var prop = CustomPropertyHelper.GetColumnInfosFromDynamicConfiguration(columnName, _configuration);
                        props.Add(prop);
                        break;
                    }
            }
            return props;
        }

        public IEnumerable<IEnumerable<CellWriteInfo>> GetRows(List<ExcelColumnInfo> props)
        {
            while (_reader.Read()) yield return GetRowValues(props);
        }

        private IEnumerable<CellWriteInfo> GetRowValues(List<ExcelColumnInfo> props)
        {
            for (int i = 0, column = 1; i < _reader.FieldCount; i++, column++)
            {
                if (_configuration.DynamicColumnFirst)
                {
                    var columnIndex = _reader.GetOrdinal(props[i].Key.ToString());
                    yield return new CellWriteInfo(_reader.GetValue(columnIndex), column, props[i]);
                }
                else
                {
                    yield return new CellWriteInfo(_reader.GetValue(i), column, props[i]);
                }
            }
        }
    }
}


